<!-- 培训资料 -->
<script setup lang="ts">
import { useLoadMore } from 'vue-request'
import { useUserInfoStore } from '@/store/userInfo'
import { fetchTrainingResourcesAPI } from '@/apis/fetchTrainingResources'

import excelIcon from '@/static/images/fileIcon/excel.png'
import pdfIcon from '@/static/images/fileIcon/pdf.png'
import pptIcon from '@/static/images/fileIcon/ppt.png'
import wordIcon from '@/static/images/fileIcon/word.png'

const userInfoStore = useUserInfoStore()

// 班级 id
const classId = ref('')

// 分页列表数据
const { dataList, loading, loadingMore, noMore, loadMore, refresh } = useLoadMore<LoadMoreData<Resource>>(
  fetchResources,
  { isNoMore: d => d?.list.length === d?.total },
)

// “加载更多”的状态
const loadMoreStatus = computed(() => {
  if (loadingMore.value)
    return 'loading'
  else if (noMore.value)
    return 'nomore'
  else
    return 'loadmore'
})

onLoad((options) => {
  if (options && options.class_id) {
    classId.value = options.class_id
    refresh()
  }
  else { uni.showToast({ title: '页面加载错误：未获取到班级id', icon: 'none' }) }
})

onReachBottom(() => loadMore())

/**
 * @description 根据传入的文件类型，获取对应的文件图标
 *
 * @param fileType - 文件类型
 */
function getFileIconByType(fileType: string) {
  if (fileType === 'docx' || fileType === 'doc')
    return wordIcon
  else if (fileType === 'ppt' || fileType === 'pptx')
    return pptIcon
  else if (fileType === 'xls' || fileType === 'xlsx')
    return excelIcon
  else if (fileType === 'pdf')
    return pdfIcon
}

/**
 * @description 分页服务函数
 */
async function fetchResources(d?: LoadMoreData<Resource>): Promise<LoadMoreData<Resource>> {
  // 缺少必要参数，先不执行
  if (!classId.value) {
    return {
      list: [],
      page: 0,
      total: 0,
    }
  }

  // 当前页数
  const _page = d?.page ? d.page + 1 : 1

  const res = await fetchTrainingResourcesAPI({
    id: classId.value,
    page: _page.toString(),
    limit: '10',
  }, userInfoStore.userInfo!.token!)

  return {
    list: res.data?.data.data || [],
    page: _page,
    total: res.data?.data.total || 9999,
  }
}

/**
 * @description 点击文件时触发
 *
 * @param file - 文件
 */
function handleTapFile(file: Resource) {
  const domain = uni.getStorageSync('domain')
  if (file.image) {
    uni.showLoading({ title: '加载中...' })
    uni.downloadFile({
      url: `${domain}${file.image}`,
      success: (res) => {
        if (res.statusCode === 200) {
          uni.saveFile({
            tempFilePath: res.tempFilePath,
            success: (res) => {
              uni.hideLoading()
              uni.openDocument({
                filePath: res.savedFilePath,
                showMenu: true,
              })
            },
            fail: (err) => {
              uni.hideLoading()
              uni.showToast({ title: JSON.stringify(err), icon: 'none' })
            },
          })
        }
      },
      fail: (err) => {
        uni.hideLoading()
        uni.showToast({ title: JSON.stringify(err), icon: 'none' })
      },
    })
  }
}
</script>

<template>
  <Spacer height="20" />
  <uv-list :custom-style="{ background: 'transparent' }">
    <uv-list-item v-for="file in dataList" :key="file.id" :custom-style="{ borderRadius: '20rpx', marginBottom: '20rpx' }">
      <view class="flex items-center rounded-20rpx bg-white p-40rpx card-shadow" @tap="handleTapFile(file)">
        <image class="h-100rpx w-93rpx flex-shrink-0" :src="getFileIconByType(file.type)" />
        <Spacer width="32" />
        <view class="text-28rpx text-#333333 leading-44rpx">
          {{ file.file_name }}
        </view>
      </view>
    </uv-list-item>
    <!-- 加载更多 -->
    <uv-load-more v-if="dataList.length > 3" :status="loadMoreStatus" @loadmore="loadMore" />
  </uv-list>
  <Spacer height="240" />
  <PageDefault v-if="dataList.length === 0">
    暂无培训资料
  </PageDefault>
  <uv-loading-page :loading="loading && !loadingMore" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
</template>

<route lang="yaml">
name: 'trainingResources'
style:
  navigationBarTitleText: '培训资料'
</route>
